package com.sliface.web.app;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.Query.FilterOperator;

public class Facade {
	private static Facade instance = null;
	private DatastoreService datastore=null;
    public static Facade getInstance(){
    	
    	if(instance==null){
    		instance = new Facade();
    	}
    	return instance;
    }
    
    private Facade(){
    	datastore = DatastoreServiceFactory.getDatastoreService();
    }
    
    public Entity register(String email,String passwd){
    	Key k = null;
    	Entity entity = new Entity("acount",email);
    	entity.setProperty("email", email);
    	entity.setProperty("passwd", passwd);
    	Transaction t = datastore.beginTransaction();
    	if(!checkAcountExist(email)){
    	     k=datastore.put(entity);
    	}
    	t.commit();
    	return entity;
    	
    }
    
    public Entity logon(String email,String passwd){
    	Entity entity = getAcountByKey(email);
    	if(!entity.getProperty("passwd").equals(passwd)){
    		entity=null;
    	}
    	return entity;
    	
    }
    
    private Entity getAcountByKey(String email){
    	 Key k = KeyFactory.createKey("acount", email);
    	 Entity entity=null;
    	 try {
    		 entity = datastore.get(k);
		 } catch (EntityNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		 }
		 return entity;
    	 
    }
    
    public Boolean checkAcountExist(String email){
   	    return getAcountByKey(email)==null?false:true;  
   	 
    }    
    

}
